/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {

        ListNode *head = l1, *p = NULL;
        ListNode *prev=NULL;

        int digit=0;
        p = head;
        while(l1 && l2) {
            digit += l1->val + l2->val;
            if (digit >= 10) {
                p->val = digit - 10;
                digit = 1;
            } else {
                p->val = digit;
                digit = 0;
            }

            if (!prev) {
                prev = p;
            } else {
                prev = prev->next;
            }

            p = p->next;
            l1 = l1->next;
            l2 = l2->next;
        }

        if (l1) {
            prev->next = l1;
            p = l1;
        }

        if (l2) {
            prev->next = l2;
            p = l2;
        }

        while(prev->next) {
            p = prev->next;
            p->val += digit;
            digit = p->val;
            if (digit >= 10) {
                p->val = digit - 10;
                digit = 1;
                prev = p;
            } else {
                digit = 0;
                break;
            }
        }

        if (digit != 0) {
            prev->next = new ListNode(digit);
        }
        return head;
    }

};


